//
//  QDStationHistoryViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/27.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

private final class QDStationLabel: UIView {
    
    /// 展示线路的文字
    let titleLabel = UILabel()
    /// 原型视图
    let circleView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        titleLabel.font = Font.regular.font(size: 14)
        titleLabel.textColor = QDColors.gray2
        titleLabel.text = "11号线"
    
        circleView.layer.cornerRadius = 3
        
        addSubview(titleLabel)
        addSubview(circleView)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



private final class QDStationHistoryTableViewCell: NWTableViewCell {
    
    /// 标题标签
    let titleLabel = UILabel()
    
    override func buildView() {
        super.buildView()
        
        bottomLineInset.left = 20
        bottomLineInset.right = 20
        bottomLineHeight = 0.5
        bottomLineView.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.9411764706, blue: 0.9333333333, alpha: 1)
        
        titleLabel.textColor = QDColors.black
        titleLabel.font = Font.regular.font(size: 16)
        
        contentView.addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.height.equalTo(22)
        }
    }
}

/// 搜索历史的控制器
final class QDStationHistoryViewController: NWTableViewController {
    
    private let nameKey = "stationName"
    private let idKey = "stationId"
    private let lineKey = "lines"
    
    /// 选中响应
    weak var selectActor: QDStationsViewSelectAction?
    
    /// 历史记录
    private lazy var historyStations: [NSDictionary] = {//文本读取
        
        guard let history = self.archiverManager.ritl_readArchiverObjects(inDocument: self.archiverManagerDocument!) as? [NSDictionary] else {
            
            return [NSDictionary]()
        }
        
        self.historyStationIds = history.map { $0["idKey"] as? String ?? ""}
        return history
    }()
    
    /// 用于遍历
    private var historyStationIds = [String]()//
    
    /// 插入
    func insertStation(stationName: String, stationId: String, lines:[String] = [String]()){
        
        //如果历史记录存在id,进行位置交换
        if historyStationIds.contains(stationId) {
            
            let index = (historyStationIds as NSArray).index(of: stationId)
            let station = historyStations.remove(at: index)
            
            //追加到第一个
            historyStations = [station] + historyStations
            tableView.reloadData()
            return
        }
        
        //如果不存在，插入到顶部
        historyStationIds = [stationId] + historyStationIds
        historyStations = [[nameKey: stationName,idKey: stationId,lineKey: lines]] + historyStations
        
        //刷新
        tableView.reloadData()
    }
    
    deinit {
        //本地覆盖保存
        let _ = try? archiverManager.ritl_startArchiver(historyStations, document: self.archiverManagerDocument!)
    }
    
    /// 搜索历史标签
    private let historyLabel = UILabel()
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
        tableView.rowHeight = 54
        tableViewConstraintInsets.top = 44
        archiverManagerDocument = "qdmetro_station_history"
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDStationHistoryTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        historyLabel.text = "历史记录"
        historyLabel.textColor = QDColors.gray2
        historyLabel.font = Font.regular.font(size: 14)
        
        view.addSubview(historyLabel)
        historyLabel.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview().offset(20)
            make.height.equalTo(20)
        }
    }
    
    
    // MARK: UITableView
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return historyStations.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let titleCell = cell as? QDStationHistoryTableViewCell {
            titleCell.titleLabel.text = historyStations[indexPath.row].value(forKey: nameKey) as? String ?? ""
        }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let station = historyStations[indexPath.row]
        
        selectActor?.stationsViewController(didSelect: station.value(forKey: nameKey) as? String ?? "", stationId: station.value(forKey: idKey) as? String ?? "", line: [])
    }
}
